import {reactive, ref} from 'vue';
import {useUserConfig as userInfo} from '/@/stores/UserInfoConfig';
import {useRouter} from "vue-router";
import {useMessage} from "/@/hooks/message";
import {initRouter} from "/@/router";

interface LoginForm {
    username: string
    password: string
}

export function useLoginFunctions() {
    const globalTitle = ref(import.meta.env.VITE_GLOBAL_TITLE?.trim() || 'HZSYSTEM');
    const router = useRouter();

    const form = reactive<LoginForm>({
        username: '',
        password: ''
    });

    const handleLogin = async () => {
        try {
            await userInfo().login(form);
            // 强制清空路由
            await initRouter();
            await router.push({ name: 'Home' });
        } catch (error) {
            console.error('登录失败:', error);
        }
    }

    const toRegister = () => {
        router.push({ name: 'Register' });
    }

    return {
        form,
        globalTitle,
        handleLogin,
        toRegister
    }
}

interface RegisterForm {
    username: string
    password: string
    password2: string
}

export function useRegisterFunctions() {
    const globalTitle = ref(import.meta.env.VITE_GLOBAL_TITLE?.trim() || 'HZSYSTEM');
    const router = useRouter();

    const form = reactive<RegisterForm>({
        username: '',
        password: '',
        password2: '',
    });

    const handleRegister = async () => {
        try {
            const timestamp = new Date().getTime();
            await userInfo().register(form);
            /**
             * 这里加query是因为新添加的登录页面有些是不用单独跳转注册页面的，
             * 注册成功后执行当前代码，页面不会刷新，加上个时间戳让url改变，引发页面刷新
             */
            await router.push({ name: 'Login', query: { refresh: timestamp } });
        } catch (error) {
            console.error('注册失败:', error);
        }
    }

    const toLogin = () => {
        router.push({ name: 'Login' });
    }

    return {
        form,
        globalTitle,
        handleRegister,
        toLogin
    }
}

export function useLogout() {
    const router = useRouter();
    const message = useMessage();

    const handleLogout = async () => {
        try {
            await userInfo().logout();
            await router.push({ name: 'Login' });
        } catch (error) {
            message.error('退出登录失败');
        }
    }

    return {
        handleLogout
    }
}